package com.example.Controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.Service.RoleService;
import com.example.Service.UserService;
import com.example.mapper.RoleMapper;
import com.example.pojo.SysRole;
import com.example.pojo.SysUser;
import com.example.pojo.Vo.SysUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserCotroller {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @RequestMapping("/user/list")
    public Object getUserList(
            Model model,
            @RequestParam(required = false,defaultValue = "3") Long pageSize,
            @RequestParam(required = false,defaultValue = "1") int pageIndex,
            @RequestParam(required = false,defaultValue = "0") Long roleId,
            SysUserVo  sysUserVo
            ){


        Page<SysUserVo> page = new Page(pageIndex,pageSize);

        sysUserVo.setUsrRoleId(roleId);
        sysUserVo.setUsrName(sysUserVo.getUsrName());

        model.addAttribute("userPager",userService.getPage(page,sysUserVo));
        model.addAttribute("roles",roleService.list());

        return "user/list";
    }

    @RequestMapping("/user/add")
    public String toadd(Model model){
        model.addAttribute("roles",roleService.list());

        return "user/add";
    }

    @RequestMapping("/user/save")
    public String add(SysUser sysUser,@RequestParam(defaultValue = "0") Long usrId,Model model){
        boolean flg = userService.saveOrUpdate(sysUser);

        if(flg){
            return "redirect:/user/list";
        }else  if(sysUser.getUsrId()==0){
            return "redirect:/user/add";
        }else {
            return "redirect:/user/edit?usrId="+sysUser.getUsrId();
        }
    }


    @RequestMapping("/user/edit")
    public String toUpdate(Long usrId, Model model){

        model.addAttribute("user",userService.getById(usrId));
        model.addAttribute("roles",roleService.list());

        return "user/edit";
    }

    @RequestMapping("/crm/user/del/{usrId}")
    @ResponseBody
    public Object del(@PathVariable Long usrId, Model model){

        Map<String,Object> resulfMap = new HashMap();
        resulfMap.put("delResult",userService.removeById(usrId));

        return resulfMap;
    }

}
